package com.todo.model.managers
{
	import com.todo.model.vos.Task;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	
	public class TaskManager extends EventDispatcher
	{
		//.........................................Properties..........................................
		
		private var _taskList:ArrayCollection;
		
		//.........................................Setters and Getters..........................................
		
		[Bindable (event="taskListChanged")]
		public function get taskList():ArrayCollection
		{
			return _taskList;
		}
		
		private var _task:Task;
		
		[Bindable (event="taskChanged")]
		public function get task():Task
		{
			return _task;
		}
		
		//.........................................Methods..........................................
		
		// -----------------------------------------------------------
		public function saveTaskList(tasks:ArrayCollection):void 
		{
			_taskList = new ArrayCollection(tasks.source);
			dispatchEvent(new Event('taskListChanged'));
		}
		
		// -----------------------------------------------------------
		public function selectTask(task:Task):void 
		{
			_task = task;
			dispatchEvent(new Event('taskChanged'));
		}
		
		// -----------------------------------------------------------
		public function deleteTask (task:Task):void 
		{
			var index:int = _taskList.getItemIndex(task);
			if( index >= 0 )
			{
				_taskList.removeItemAt( index );
			}
			// clear out the selected task just in case
			selectTask(null);
		}
		
		// -----------------------------------------------------------
		public function saveTask (task:Task) : void {
			
			// assume the edited fields are not an existing task, but a new task
			// and set the ArrayCollection index to -1, which means this task is not in our existing
			// task list anywhere
			var dpIndex : int = -1;
			
			// loop thru the task list
			for ( var i : uint = 0; i < taskList.length; i++ ) 
			{
				// if the emp_id of the incoming task matches an task already in the list
				if ( taskList[i].id == task.id ) {
					// set our ArrayCollection index to that task position
					dpIndex = i;
				}
			}
			
			// if it was an existing task already in the ArrayCollection
			if ( dpIndex >= 0 ) {
				// update that task's values
				(taskList.getItemAt(dpIndex) as Task).copyFrom(task);
			}
				// otherwise, if it didn't match any existing tasks
			else 
			{
				// add the temp task to the ArrayCollection
				var tempTask:Task = new Task();
				tempTask.copyFrom(task);
				taskList.addItem(tempTask);
			}
			
			// clear out the selected task
			selectTask(null);
			
		}
	}
}